using ERP.Common.Results;
using ERP.ERPSystem.WarehouseManagement;
using ERP.ERPSystem.WarehouseManagement.Dto;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace ERP.Web.Controllers.WarehouseManagement
{
    /// <summary>
    /// 来料检验控制器
    /// </summary>
    public class IncomingInspectionController : Controller
    {
        private readonly IIncomingInspectionServices _incomingInspectionServices;

        public IncomingInspectionController(IIncomingInspectionServices incomingInspectionServices)
        {
            _incomingInspectionServices = incomingInspectionServices;
        }

        /// <summary>
        /// 来料检验主页面
        /// </summary>
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 来料检验表单页面
        /// </summary>
        public IActionResult Form()
        {
            return View();
        }

        /// <summary>
        /// 分页查询来料检验记录
        /// </summary>
        [HttpPost]
        public async Task<JsonResult> GetPagedList()
        {
            try
            {
                // 直接创建查询DTO，避免模型验证问题
                var queryDto = new IncomingInspectionQueryDto
                {
                    Page = Request.Form.ContainsKey("page") ? int.Parse(Request.Form["page"]) : 1,
                    Limit = Request.Form.ContainsKey("limit") ? int.Parse(Request.Form["limit"]) : 10,
                    IncomingInspectionCode = Request.Form.ContainsKey("incomingInspectionCode") ? Request.Form["incomingInspectionCode"].ToString() : null,
                    IncomingInspectionName = Request.Form.ContainsKey("incomingInspectionName") ? Request.Form["incomingInspectionName"].ToString() : null,
                    IncomingInspectionJName = Request.Form.ContainsKey("incomingInspectionJName") ? Request.Form["incomingInspectionJName"].ToString() : null,
                    ProductCode = Request.Form.ContainsKey("productCode") ? Request.Form["productCode"].ToString() : null,
                    ProductName = Request.Form.ContainsKey("productName") ? Request.Form["productName"].ToString() : null,
                    TestingResult = Request.Form.ContainsKey("testingResult") ? Request.Form["testingResult"].ToString() : null,
                    TestingPerson = Request.Form.ContainsKey("testingPerson") ? Request.Form["testingPerson"].ToString() : null
                };

                // 处理日期范围
                if (Request.Form.ContainsKey("incomingDateStart") && !string.IsNullOrEmpty(Request.Form["incomingDateStart"]))
                {
                    if (DateTime.TryParse(Request.Form["incomingDateStart"], out DateTime incomingStart))
                        queryDto.IncomingDateStart = incomingStart;
                }
                
                if (Request.Form.ContainsKey("incomingDateEnd") && !string.IsNullOrEmpty(Request.Form["incomingDateEnd"]))
                {
                    if (DateTime.TryParse(Request.Form["incomingDateEnd"], out DateTime incomingEnd))
                        queryDto.IncomingDateEnd = incomingEnd;
                }

                if (Request.Form.ContainsKey("testingDateStart") && !string.IsNullOrEmpty(Request.Form["testingDateStart"]))
                {
                    if (DateTime.TryParse(Request.Form["testingDateStart"], out DateTime testingStart))
                        queryDto.TestingDateStart = testingStart;
                }

                if (Request.Form.ContainsKey("testingDateEnd") && !string.IsNullOrEmpty(Request.Form["testingDateEnd"]))
                {
                    if (DateTime.TryParse(Request.Form["testingDateEnd"], out DateTime testingEnd))
                        queryDto.TestingDateEnd = testingEnd;
                }

                var result = await _incomingInspectionServices.GetPagedListAsync(queryDto);
                return Json(new SimpleAPIResult
                {
                    Success = true,
                    Code = EnumResult.查询成功,
                    Message = "查询成功",
                    Data = result
                });
            }
            catch (System.Exception ex)
            {
                return Json(new SimpleAPIResult
                {
                    Success = false,
                    Code = EnumResult.查询失败,
                    Message = ex.Message,
                    Data = null
                });
            }
        }

        /// <summary>
        /// 根据ID获取来料检验记录
        /// </summary>
        [HttpGet]
        public async Task<JsonResult> GetById(int id)
        {
            try
            {
                var result = await _incomingInspectionServices.GetByIdAsync(id);
                return Json(new SimpleAPIResult
                {
                    Success = true,
                    Code = EnumResult.查询成功,
                    Message = "查询成功",
                    Data = result
                });
            }
            catch (System.Exception ex)
            {
                return Json(new SimpleAPIResult
                {
                    Success = false,
                    Code = EnumResult.查询失败,
                    Message = ex.Message,
                    Data = null
                });
            }
        }

        /// <summary>
        /// 新增来料检验记录
        /// </summary>
        [HttpPost]
        public async Task<JsonResult> Create([FromBody] IncomingInspectionCreateDto createDto)
        {
            try
            {
                var result = await _incomingInspectionServices.CreateAsync(createDto);
                return Json(new SimpleAPIResult
                {
                    Success = result,
                    Code = result ? EnumResult.创建成功 : EnumResult.创建失败,
                    Message = result ? "创建成功" : "创建失败",
                    Data = null
                });
            }
            catch (System.Exception ex)
            {
                return Json(new SimpleAPIResult
                {
                    Success = false,
                    Code = EnumResult.创建失败,
                    Message = ex.Message,
                    Data = null
                });
            }
        }

        /// <summary>
        /// 更新来料检验记录
        /// </summary>
        [HttpPost]
        public async Task<JsonResult> Update([FromBody] IncomingInspectionUpdateDto updateDto)
        {
            try
            {
                var result = await _incomingInspectionServices.UpdateAsync(updateDto);
                return Json(new SimpleAPIResult
                {
                    Success = result,
                    Code = result ? EnumResult.更新成功 : EnumResult.更新失败,
                    Message = result ? "更新成功" : "更新失败",
                    Data = null
                });
            }
            catch (System.Exception ex)
            {
                return Json(new SimpleAPIResult
                {
                    Success = false,
                    Code = EnumResult.更新失败,
                    Message = ex.Message,
                    Data = null
                });
            }
        }

        /// <summary>
        /// 删除来料检验记录
        /// </summary>
        [HttpPost]
        public async Task<JsonResult> Delete(int id)
        {
            try
            {
                var result = await _incomingInspectionServices.DeleteAsync(id);
                return Json(new SimpleAPIResult
                {
                    Success = result,
                    Code = result ? EnumResult.删除成功 : EnumResult.删除失败,
                    Message = result ? "删除成功" : "删除失败",
                    Data = null
                });
            }
            catch (System.Exception ex)
            {
                return Json(new SimpleAPIResult
                {
                    Success = false,
                    Code = EnumResult.删除失败,
                    Message = ex.Message,
                    Data = null
                });
            }
        }

        /// <summary>
        /// 批量删除来料检验记录
        /// </summary>
        [HttpPost]
        public async Task<JsonResult> BatchDelete([FromBody] List<int> ids)
        {
            try
            {
                var result = await _incomingInspectionServices.BatchDeleteAsync(ids);
                return Json(new SimpleAPIResult
                {
                    Success = result,
                    Code = result ? EnumResult.删除成功 : EnumResult.删除失败,
                    Message = result ? "批量删除成功" : "批量删除失败",
                    Data = null
                });
            }
            catch (System.Exception ex)
            {
                return Json(new SimpleAPIResult
                {
                    Success = false,
                    Code = EnumResult.删除失败,
                    Message = ex.Message,
                    Data = null
                });
            }
        }

        /// <summary>
        /// 生成来料检验单编号
        /// </summary>
        [HttpPost]
        public JsonResult GenerateCode(string prefix = "LL")
        {
            try
            {
                // 生成编号格式：LL + 雪花ID
                var snowflakeId = GenerateSnowflakeId();
                var code = prefix + snowflakeId;
                
                return Json(new SimpleAPIResult
                {
                    Success = true,
                    Code = EnumResult.查询成功,
                    Message = "生成成功",
                    Data = code
                });
            }
            catch (System.Exception ex)
            {
                return Json(new SimpleAPIResult
                {
                    Success = false,
                    Code = EnumResult.查询失败,
                    Message = ex.Message,
                    Data = null
                });
            }
        }

        /// <summary>
        /// 生成雪花ID
        /// </summary>
        private long GenerateSnowflakeId()
        {
            // 简化的雪花ID算法实现
            var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            var machineId = 1; // 机器ID，可以根据实际情况配置
            var random = new Random();
            var sequence = random.Next(0, 4096); // 序列号，0-4095
            
            // 雪花ID结构：时间戳(41位) + 机器ID(10位) + 序列号(12位)
            var snowflakeId = ((timestamp - 1288834974657L) << 22) | (machineId << 12) | sequence;
            
            return snowflakeId;
        }
    }
} 